﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Diagnostics;
using LogLib;
using ComClassLibrary;
using KeyboardArg;

namespace SoftKeyBoard
{
    static class Program
    {
        private static string ToolName = "PhoneNumberKeyBoard";

        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {          
            KillExistProgress();
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            string jsonString = "";
            if (args.Length <= 0)
            {
                jsonString = "{\"Content\":\"19934560654\",\"Key\":null,\"Lang\":null,\"MaxLength\":5,\"Title\":\"请输入你的电话号码\",\"VoiceFileName\":null,\"Wnd\":{\"Code\":5903714}}";
            }
            else
            {
                jsonString = args[0].Replace('@', '"'); ;
            }
            KeyBoardArgs keyBoardArgs = null;
            try
            {
                keyBoardArgs = JsonHandler.ConvertToJsonObject<KeyBoardArgs>(jsonString);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                Log.WriteException(e.ToString());
                MessageBox.Show(e.ToString(), "参数错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            if (null == keyBoardArgs)
            {
                Log.WriteAsync("参数错误, 启动失败.");
                MessageBox.Show(jsonString, "参数错误", MessageBoxButtons.OK, MessageBoxIcon.Error); //20170412 取消提示
                return;
            }
            Application.Run(new FormInputPhoneNumber(keyBoardArgs));
        }

        private static void KillExistProgress()
        {
            Process p = Process.GetCurrentProcess();
            Process[] processes = Process.GetProcesses();
            foreach (System.Diagnostics.Process process in processes)
            {
                if (process.ProcessName.Contains(ToolName) && p.Id != process.Id)
                {
                    Log.WriteAsync("发现已存在进程，开始等待进程退出.");
                    process.WaitForExit(2000);
                    if (!process.HasExited)
                    {
                        process.Kill();
                        Log.WriteAsync("强制退出老进程");
                    }
                    Log.WriteAsync("老进程已经退出.");
                }
            }
        }
    }
}
